package cn.tedu.knows.portal.security;

import cn.tedu.knows.portal.service.impl.UserDetailsServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
//启动Spring Security的权限管理功能
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends
                        WebSecurityConfigurerAdapter {
    //首先从Spring容器中获得我们编写的用户名密码登录的对象
    @Autowired
    private UserDetailsServiceImpl userDetailsService;
    @Override
    protected void configure(
            AuthenticationManagerBuilder auth) throws Exception {
        // 这个方法就是Spring Security提供的方法
        // 它会获得我们编写代码返回的UserDetails对象,并进行登录验证
        auth.userDetailsService(userDetailsService);
    }

    //Spring Security框架默认是所有资源都需要登录才能访问
    //实际上是不合理的,我们通过下面的方法进行指定资源不需要登录就能访问
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests() // 设置请求限制
            .antMatchers(        // 指定受影响资源
                   // "/index_student.html",
                    "/img/**",
                    "/js/*",
                    "/css/*",
                    "/bower_components/**",
                    "/login.html",
                    "/register.html",
                    "/register"
            ).permitAll() //全部允许,不登录就能访问
            .anyRequest()//其它请求
            .authenticated() //需要登录才能访问
            .and()  //上面设置完了,开始别的设置
            .formLogin()//使用表单登录
            .loginPage("/login.html")//自定义登录页面
            .loginProcessingUrl("/login")//设置登录提交路径
            .failureUrl("/login.html?error")//登录失败时跳转的页面
            .defaultSuccessUrl("/index.html")//登录成功跳转的页面
            .and() //登录设置完毕
            .logout()  //开始设置登出
            .logoutUrl("/logout")//访问这个路径就是登出了
            .logoutSuccessUrl("/login.html?logout")//登出之后跳转到登录页
            .and().csrf().disable(); //关闭防跨域攻击,微服务时会讲
    }
}
